from flask import Flask, render_template, send_from_directory
from flask_socketio import SocketIO, emit
import uuid

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

save_file = 'write_content.txt'
cursor_dict = {}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/static/<path:path>')
def send_static(path):
    return send_from_directory('static', path)

@socketio.on('connect')
def handle_connect():
    user_id = str(uuid.uuid4())
    emit('assign_id', {'user_id': user_id})
    print(f'Client connected: {user_id}')

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

@socketio.on('update_document')
def handle_update_document(data):
    with open(save_file, 'w') as f:
        f.write(data)
    emit('update_document', data, broadcast=True)

@socketio.on('update_cursor')
def handle_update_cursor(data):
    print(data)
    emit('update_cursor', data, broadcast=True)

if __name__ == '__main__':
    socketio.run(app, debug=True)
